using System;
using System.IO;
using System.Net;
using Autofac;
using Koonfusion.SyncDeploy.Core.Manifest;
using Koonfusion.SyncDeploy.Core.Services;

namespace Koonfusion.SyncDeploy.Core
{
    public class ManifestExtractor : ManifestProcessorBase
    {
        public override event EventHandler OnStart;
        public override event EventHandler OnSuccess;
        public override event FileProcessedEventHandler OnFileProcessed;

        public ManifestExtractor()
        {
            var builder = new ContainerBuilder();
            builder.Register<IDownloadService>(c => new DownloadService());

            fac = builder.Build();
        }

        public void ExtractPackage(Uri packageManifest, DirectoryInfo destination)
        {
            var manifest = new ManifestService().Read(packageManifest);

            foreach (var file in manifest.Files)
            {
                var currentFile = new FileInfo(Path.Combine(destination.FullName.Trim('\\'), file.Target.Trim('\\')));

                if (currentFile.Exists)
                {
                    Console.WriteLine("File '{0}' exists. checking if file are same.", destination.FullName);
                    if (file.RawSize != currentFile.Length)
                    {
                        Console.WriteLine("File size mismatch");
                        GetFile(packageManifest, file, currentFile);
                    }
                    else if (file.Hash != FileUtilities.GetHash(currentFile))
                    {
                        Console.WriteLine("File hash mismatch");
                        GetFile(packageManifest, file, currentFile);
                    }
                    else
                    {
                        Console.WriteLine("File are identical. skipping");
                    }
                }
                else
                {
                    GetFile(packageManifest, file, currentFile);
                }
            }
        }

  

        private void GetFile(Uri packageManifest, SyncFile file, FileInfo destination)
        {


            Console.WriteLine("Downloading File '{0}'", destination.FullName);
            if (!destination.Directory.Exists)
            {
                Console.WriteLine("Creating Directory '{0}'", destination.Directory.FullName);
                destination.Directory.Create();
            }

            var webClinet = new WebClient();

            //File has to be uncompressed
            //webClinet.DownloadFile(string.Format("{0}/{1}.zip", packageManifest, file.Hash),);
        }



  
    }
}